package top.lyc829.leetcode.T25;


import java.util.List;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {

        if (k == 1) {
            return head;
        }

        ListNode hair = new ListNode(0, head);
        ListNode pre = hair;

        while (head != null) {
            ListNode tail = pre;
            for(int i = 0; i < k; i++) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            ListNode next = tail.next;

            ListNode[] res = reverseListNode(head, tail);
            head = res[0];
            tail = res[1];
            pre.next = head;
            tail.next = next;

            pre = tail;
            head = next;
        }


        return hair.next;

    }

    private ListNode[] reverseListNode(ListNode head, ListNode tail) {

        ListNode pre = tail.next;
        ListNode curr = head;


        while (pre != tail) {
            ListNode next = curr.next;
            curr.next = pre;

            pre = curr;
            curr = next;
        }

        return new ListNode[] {tail, head};

    }

    public static void main(String[] args) {

        ListNode listNode = initNode();

        Solution s = new Solution();
        ListNode head = s.reverseKGroup(listNode, 2);

        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    /**
     * 初始化链表
     * @return
     */
    private static ListNode initNode() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, null))));
//        ListNode head = new ListNode(1, new ListNode(2, null));

        return head;
    }
}